package com.hkd.forum.controller;

import com.hkd.forum.common.AppResult;
import com.hkd.forum.common.ResultCode;
import com.hkd.forum.config.AppConfig;
import com.hkd.forum.model.Message;
import com.hkd.forum.model.User;
import com.hkd.forum.service.IMessageService;
import com.hkd.forum.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "站内信接口")
@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IUserService userService;
    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam(value = "接收⽤⼾Id") @RequestParam(value = "receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam(value = "站内信内容") @RequestParam(value = "content") @NonNull String content){

        //1.检测用户状态是否被禁言

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user != null && user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //2.不能自己给自己发
        if(user.getId() == receiveUserId){
            return AppResult.failed(ResultCode.FAILED_SEND_TO_SELF);
        }

        //3.校验接受者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser != null && receiveUser.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //4.封装对象
        Message message = new Message();
        message.setPostUserId(user.getId());//发送者Id
        message.setReceiveUserId(receiveUserId);//接受者Id
        message.setContent(content);//站内信内容

        //5.调用Service
        messageService.create(message);
        //返回结果
        return AppResult.success();
    }
    @ApiOperation("获取未读数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request){
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //获取未读数
        Integer unreadCount = messageService.selectUnreadCount(user.getId());
        //返回结果
        return AppResult.success(unreadCount);
    }

    @ApiOperation("查询用户所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        //获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //获取所有站内信
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        //返回结果
        return AppResult.success(messages);
    }
    @PostMapping("/markRead")
    @ApiOperation("更新状态已读")
    public AppResult markRead(@ApiParam("站内信Id") @RequestParam("id") @NonNull Long id,
                              HttpServletRequest request){
        //校验站内信是否存在
        Message message = messageService.selectById(id);
        if(message == null){
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //校验站内信是不是自己
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        if(message.getReceiveUserId() != user.getId()){
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_YOURS);
        }
        //更新状态已读
        messageService.updateStateById(id, (byte) 1);
        //返回结果
        return AppResult.success();
    }

    /**
     * 回复站内信
     * @param request
     * @param repliedId 要回复的站内信Id
     * @param content 站内信的内容
     * @return AppResult
     */
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                            @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                            @ApiParam("站内信的内容") @RequestParam("content") @NonNull String content){
        //校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if(existsMessage == null || existsMessage.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //不能自己回复
        if(user.getId() == existsMessage.getPostUserId()){
            return AppResult.failed(ResultCode.FAILED_SEND_TO_SELF);
        }

        //构造数据对象
        Message message = new Message();
        message.setPostUserId(user.getId());//发送者
        message.setReceiveUserId(existsMessage.getPostUserId()); //接受者
        message.setContent(content);

        //调用Service
        messageService.reply(repliedId,message);

        //返回结果
        return AppResult.success();


    }
}
